package utils

import (
	"fmt"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnNMEA0183Checksum{})
	if err != nil {
		panic(err)
	}
}

type fnNMEA0183Checksum struct{}

func (fnNMEA0183Checksum) Name() string {
	return "nmea0183Checksum"
}

func (fnNMEA0183Checksum) Sig() ([]data.Type, bool) {
	return []data.Type{data.TypeString}, false
}

func (fnNMEA0183Checksum) Eval(params ...interface{}) (interface{}, error) {
	if len(params) != 1 {
		return nil, fmt.Errorf("expect 1 arguments, got %d", len(params))
	}
	payload, err := coerce.ToString(params[0])
	if err != nil {
		return nil, err
	}
	s := XorChecksumString([]byte(payload))
	return s, nil
}
